/**
 * 批量替换$t(key)里的key值
 * npm run i18n2 path
 *
 * path 需要替换的目录，从项目目录开始 npm run i18n2 'packages/web/src/views/app'
 *
 * 输出outPut文件夹
 *  log.json
 *    failKey 未匹配到词条的中文
 *    successKey 成功配到词条的中文
 *    unReplaceFile 未找到中文能进行替换的文件
 *    lostConfig 未配置中英文双语的i18n词条
 */

const fs = require('fs');
const path = require('path');
const { chalk } = require('@vue/cli-shared-utils');
// const axios = require('axios');

const log = {
  info(msg) {
    console.log(chalk.green(msg));
  },
  error(msg) {
    console.log(chalk.red(msg));
  },
  warnning(msg) {
    console.log(chalk.yellow(msg));
  }
};

// 获取文件列表
function getFileListForPath(path) {
  try {
    const list = fs.readdirSync(path, { encoding: 'utf-8' });
    return list.map(item => {
      const itemPath = `${path}/${item}`;
      const isFile = fs.statSync(itemPath).isFile();
      return isFile ? itemPath : getFileListForPath(itemPath);
    });
  } catch (e) {
    log.error('解释目录失败：' + path);
    process.exit();
  }
}

// 所有文件夹下获取到的Vue、js文件
function getFiles(replacePath) {
  const foldPath = path.resolve(__dirname, '../', replacePath);
  const files = getFileListForPath(foldPath);
  return files.flat(Infinity).filter(pathItem => /vue|js/.test(pathItem));
}

// 获取字典
async function getJson() {
  try {
    const json = fs.readFileSync(`./scripts/json.json`, {
      encoding: 'utf-8'
    });
    return {
      json: JSON.parse(json)
    };
  } catch (e) {
    log.error('加载json.json文件失败: 请检查 scripts/json.json 是否存在');
    process.exit();
  }
}

// 开始替换
async function start(replacePath) {
  if (!fs.existsSync('./outPut')) {
    fs.mkdirSync('./outPut');
  }

  const failKey = [];
  const matchFile = [];

  const { json: replaceDict } = await getJson();
  const files = getFiles(replacePath); // replacePath目录下所有vue js 文件

  // console.log(files);
  files.forEach(pathItem => {
    // 读取文件
    let file = fs.readFileSync(pathItem, { encoding: 'utf-8' });

    const i18nKeys = file.match(/\$t\(\'[a-zA-Z0-9-_.]+\'\)/g);

    const i18nKeys2 = file.match(/\$t\([a-zA-Z_][^\)]*\)/g);
    if (i18nKeys2 && i18nKeys2.length) {
      matchFile.push(`${pathItem}-${i18nKeys2}`);
    }

    if (i18nKeys && i18nKeys.length) {
      i18nKeys.forEach(i18nKeyItem => {
        const i18nKeyItemCode = i18nKeyItem.slice(4, -2);
        let reg;
        try {
          reg = new RegExp(`\\$t\\(\\'${i18nKeyItemCode}\\'\\)`, 'g');
        } catch (err) {
          failKey.push(`${pathItem}-${i18nKeyItem}`);
          // console.warn(err);
        }
        if (replaceDict[i18nKeyItemCode] && reg) {
          const i18nKey = replaceDict[i18nKeyItem.slice(4, -2)]; // i18n词条
          file = file.replace(reg, `$t('${i18nKey}')`); // 中文替换为词条
          // console.log('----------------------', file);
        } else {
          // failKey.push(`${pathItem}-${i18nKeyItem}`);
        }
      });

      fs.writeFileSync(`${pathItem}`, file, {
        encoding: 'utf-8'
      });
    } else {
      // unReplaceFile.push(pathItem);
    }
  });

  // 写日志
  fs.writeFileSync(
    `./outPut/log.json`,
    JSON.stringify({
      failKey: [...new Set(failKey)],
      // successKey: [...new Set(successKey)],
      // unReplaceFile: [...new Set(unReplaceFile)],
      // lostConfig
      matchFile
    }),
    {
      encoding: 'utf-8'
    }
  );
  console.log('---------------执行完毕---------------');

  // console.log(`
  //   \n\n\n\n
  //   执行完成，请查看./outPut/log.json\n
  //   请自行检查对比替换的内容！
  // `);
}

console.log(process.argv);
const replacePath = process.argv[2];
if (!replacePath) {
  log.error('请输入文件夹类路径');
  log.warnning('   pnpm run i18n path [token]');
} else {
  start(replacePath);
}
